import { SettingsService, MenuService } from '@delon/theme';
import { Component, OnDestroy, Inject, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import {
  SocialService,
  SocialOpenType,
  TokenService,
  DA_SERVICE_TOKEN,
} from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { environment } from '@env/environment';
import { StartupService } from '@core/startup/startup.service';
import { UserService } from 'app/my/user/user.service';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [SocialService],
})
export class UserLoginComponent implements OnDestroy {
  form: FormGroup;
  error = '';
  type = 0;
  loading = false;

  constructor(
    fb: FormBuilder,
    private router: Router,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private settingsService: SettingsService,
    private socialService: SocialService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
    private startupSrv: StartupService,
    private userService: UserService,
    private menuService: MenuService,
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(1)]],
      password: [null, Validators.required],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true],
      loginType: 0
    });
    modalSrv.closeAll();

    this.form.controls["userName"].setValue(localStorage.getItem("userName"));
    this.form.controls["password"].setValue(localStorage.getItem("password"));
    this.form.controls["mobile"].setValue(localStorage.getItem("mobile"));
    this.form.controls["remember"].setValue(localStorage.getItem("remember"));
  }

  // region: fields

  get userName() {
    return this.form.controls.userName;
  }
  get password() {
    return this.form.controls.password;
  }
  get mobile() {
    return this.form.controls.mobile;
  }
  get captcha() {
    return this.form.controls.captcha;
  }

  // endregion

  switch(ret: any) {
    this.type = ret.index;
    // 登录类型手机或账号
    this.form.controls["loginType"].setValue(this.type);
  }

  // region: get captcha

  count = 0;
  interval$: any;

  getCaptcha() {
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0) clearInterval(this.interval$);
    }, 1000);
  }

  // endregion

  submit() {
    this.error = '';
    if (this.type === 0) {
      this.userName.markAsDirty();
      this.userName.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.userName.invalid || this.password.invalid) return;
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) return;
    }

    // mock http
    this.loading = true;

    /*
    // 清空路由复用信息
    this.reuseTabService.clear();
    // 设置Token信息
    this.tokenService.set({
      token: '123456789',
      name: this.userName.value,
      email: `cipchk@qq.com`,
      id: 10000,
      time: +new Date(),
    });
    // 重新获取 StartupService 内容，若其包括 User 有关的信息的话
    // this.startupSrv.load().then(() => this.router.navigate(['/']));
    // 否则直接跳转
    this.router.navigate(['/']);
    */

    this.userService.login(this.form.value).subscribe(resp => {
      this.loading = false;
      if (resp.success) {
        if (this.form.value.remember) {
          localStorage.setItem("remember", this.form.value.remember);  
          localStorage.setItem("userName", this.form.value.userName);
          localStorage.setItem("password", this.form.value.password);

          if (this.form.value.mobile != null)
            localStorage.setItem("mobile", this.form.value.mobile);

        } else {
          localStorage.setItem("userName", "");
          localStorage.setItem("password", "");
          localStorage.setItem("mobile", "");
          localStorage.setItem("remember", "");
        }

        localStorage.setItem("employee", JSON.stringify(resp.infos[0]));

        // 清空路由复用信息
        this.reuseTabService.clear();

        this.tokenService.set({
          employeeList: resp.infos,
          token: resp.token,
          // enterprise: resp.infos[0].enterpriseName,
          // department: resp.infos[0].deptName,
          // name: resp.infos[0].name,
          // email: resp.infos[0].email,
          // id: 10000,
          time: + new Date
        });

        let roleId = resp.infos[0].roleId;

        // 导航菜单
        this.userService.getMenu(roleId).subscribe(resp => {
          if (resp.success) {
            this.menuService.clear();
            this.menuService.add(resp.menu);

            var cache = [];
            let str = JSON.stringify(this.menuService.menus, function (key, value) {
              if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                  // Circular reference found, discard key
                  return;
                }
                // Store value in our collection
                cache.push(value);
              }
              return value;
            });
            cache = null; // Enable garbage collection

            localStorage.setItem("naviMenu", str);
          }
          else {
            this.error = resp.errorMsg;
            return;
          }

        }, error => {
          this.error = resp.errorMsg;
          return;
        });

        this.router.navigate(['/']);

      } else {
        this.error = resp.errorMsg;
        return;
      }

    }, error => {
      this.loading = false;
      this.error = "服务器异常, 稍后重试!";
    });

  }

  // region: social

  open(type: string, openType: SocialOpenType = 'href') {
    let url = ``;
    let callback = ``;
    if (environment.production)
      callback = 'https://cipchk.github.io/ng-alain/callback/' + type;
    else callback = 'http://localhost:4200/callback/' + type;
    switch (type) {
      case 'auth0':
        url = `//cipchk.auth0.com/login?client=8gcNydIDzGBYxzqV0Vm1CX_RXH-wsWo5&redirect_uri=${decodeURIComponent(
          callback,
        )}`;
        break;
      case 'github':
        url = `//github.com/login/oauth/authorize?client_id=9d6baae4b04a23fcafa2&response_type=code&redirect_uri=${decodeURIComponent(
          callback,
        )}`;
        break;
      case 'weibo':
        url = `https://api.weibo.com/oauth2/authorize?client_id=1239507802&response_type=code&redirect_uri=${decodeURIComponent(
          callback,
        )}`;
        break;
    }
    if (openType === 'window') {
      this.socialService
        .login(url, '/', {
          type: 'window',
        })
        .subscribe(res => {
          if (res) {
            this.settingsService.setUser(res);
            this.router.navigateByUrl('/');
          }
        });
    } else {
      this.socialService.login(url, '/', {
        type: 'href',
      });
    }
  }

  // endregion

  ngOnDestroy(): void {
    if (this.interval$) clearInterval(this.interval$);
  }
}
